<template>
  <text :style="textStyle" class="text">{{ pageModule.currentText }}</text>
</template>

<script setup lang="ts">
  import { defineProps, reactive, onMounted, defineEmits } from "vue";

  const props = defineProps({
    text: {
      type: String,
      default: '',
    },
    speed: {
      type: Number,
      default: 30, // 打字速度，单位：毫秒
    },
    cancelWhiter: {
      type: Boolean,
      default: true
    },
    textStyle: {
      type: Object,
      default: () => ({}), // 文字样式对象
    }
  });

  const emit = defineEmits(['onEnd', 'onStart', 'onWriter']);

  const pageModule = reactive({
    currentText: '', // 当前显示的文字
    currentIndex: 0, // 当前文字的索引
    typingFinished: false, // 打字完成的标志
  });

  const startTyping = () => {
    if (props.text && props.cancelWhiter) {
      emit('onStart');
      const textLength = props.text.length;
      const typingInterval = setInterval(() => {
        if (pageModule.currentIndex < textLength) {
          emit('onWriter');
          pageModule.currentText += props.text[pageModule.currentIndex];
          pageModule.currentIndex++;
        } else {
          clearInterval(typingInterval);
          emit('onEnd');
          pageModule.typingFinished = true;
        }
      }, props.speed);
    } else {
      emit('onStart');
      pageModule.currentText = props.text;
      emit('onEnd');
    }
  }

  onMounted(() => {
    startTyping();
  });
</script>

<style scoped>
</style>